class ContactsController < ApplicationController
  layout "m"

    before_filter :login_required
    before_filter :group_setup
    
    def group_setup
      if params[:group_id]
        @group_id = params[:group_id]
      elsif current_user.groups.size == 1
        @group_id = current_user.groups[0].id
      else
        @group_id =1
        #flash[:notice] = "Your group was not selected or does not exist"
        #redirect_to :controller => 'groups', :action => :index
      end
    end
    
    def edit
      @contact = Contact.find(params[:id])
      @contact_entries = ContactEntry.find(:all, :conditions =>["contact_id = ?", params[:id]], :order => "created_at ASC")
      @users = User.find(:all)
      return unless request.post?
      entry = ContactEntry.new(params[:contact_entry])
      entry.created_by = current_user
      @contact.contact_entries << entry
      if @contact.first_entry.status == "Closed"
        @contact.status = 0
      else
        @contact.status = 1
      end
      @contact.shead = entry.fname + " " + entry.lname
      @contact.sbody = entry.note
      @contact.smeta = entry.note
      if @contact.save
        redirect_to :action => 'edit'
      else
          flash[:error] = entry.errors.full_messages
      end
    end
    def list
      if params[:viewoptions]
        current_user.pref3 = params[:viewoptions][:view]
        current_user.save!
      end
      @contacts = Contact.find(:all, :conditions=>["status!=0"])
      if current_user.pref3 == "first name"
        @contacts = @contacts.sort_by{|x| x.first_entry.fname.downcase }
      elsif current_user.pref3 == "last name"
        @contacts = @contacts.sort_by{|x| x.first_entry.lname.downcase }
      else
        @contacts = @contacts.sort_by{|x| x.first_entry.created_at }.reverse!
      end
      render :partial => 'list'
    end
    def index
    end

    def new
      # save action item and entry
      @contact = Contact.new(params[:contact])    
      return unless request.post? 
      entry = ContactEntry.new(params[:contact_entry])
      entry.created_by = current_user
      @contact.status = 1
      @contact.shead = entry.fname + " " + entry.lname
      @contact.sbody = entry.note
      @contact.smeta = entry.note
      @contact.contact_entries << entry
      if @contact.save
        redirect_to :action => 'index'
      else
        flash[:error] = entry.errors.full_messages
      end
    end

  end
